package org.j5108.controller;

import java.util.*;

import org.j5108.beans.Product;
import org.j5108.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;

/**
 * 商品类的控制器
 */
@Controller
@RequestMapping(value = "/products")
public class ProductController {
    @Autowired
    private ProductService productService;
    @RequestMapping(value="/show")
    public String show( Model model ) {
        // 调用业务逻辑类获得商品列表
        List<Product> productList = productService.getAllProducts();
        model.addAttribute("products", productList);
        return "show";
    }

    @RequestMapping(value="/all")
    public ModelAndView testModelAndView() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("products", productService.getAllProducts());
        modelAndView.setViewName("show");
        return modelAndView;
    }

    @RequestMapping(value="/showAll")
    public String testMapParam( Map<String, Object > map ) {
        // 测试map参数
        map.put("products",productService.getAllProducts());
        return "show";
    }

    @RequestMapping(value="/api")
    public String testServletAPI( HttpServletRequest request ) {
        request.setAttribute("products",productService.getAllProducts());
        return "show";
    }
    /**
     * REST风格URL
     * @param productId 由@PathVariable获取到URL中的{id}的值并赋值给productId
     * @return
     */
    @RequestMapping(value="/get/{id}")
    public String testPathVariable( @PathVariable("id") Integer productId, Model model ) {

        Product pro = productService.getProductById(productId);
        model.addAttribute("product", pro);
        return "product";
    }
    @RequestMapping(value="/info")
    public String testRequestParam( @RequestParam("id") Integer productId,Model model){
        Product pro = productService.getProductById(productId);
        model.addAttribute("product", pro);
        return "product";
    }
    @RequestMapping(value="/edit/{id}")
    public String edit(@PathVariable("id") Integer id , Model model) {
        Product pro = productService.getProductById(id);
        model.addAttribute("command", pro);
        return "modify";
    }
    @RequestMapping(value="/Modify")
    public String modify( Product product, Model model ) {
        productService.resetProductById(product);
        model.addAttribute("products", productService.getAllProducts());
        return "show";
    }
}
